package com.coocaa.ops.common.tool.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author bijiahao
 * @date : 2019/1/11.
 * @description: 多线程 ThreadFactory工厂 可指定线程名称
 *
 */
@Slf4j
public class NamedThreadFactory implements ThreadFactory {
    /**
     * 默认名称
     */
    private static final String DEFAULT_NAME = "data-sync-pool";
    /**
     * 线程名称
     */
    private final String name;
    /**
     * 是否守护线程
     */
    private final boolean daemon;
    /**
     * 线程组
     */
    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(0);

    private static final Thread.UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER = (t, e) -> log.error("from " + t.getName(), e);

    public NamedThreadFactory() {
        this(DEFAULT_NAME, true);
    }

    public NamedThreadFactory(String name) {
        this(name, true);
    }

    public NamedThreadFactory(String name, boolean daemon) {
        this.name = name;
        this.daemon = daemon;
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(threadGroup, r, name + "-" + threadNumber.getAndIncrement(), 0);
        t.setDaemon(daemon);
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }

        t.setUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER);
        return t;
    }
}
